package cn.lin.serviceImpl;

import cn.lin.dao.UserDao;
import cn.lin.daoImpl.UserDaoImpl;
import cn.lin.domain.PageBean;
import cn.lin.domain.User;
import cn.lin.service.UserService;

import java.util.List;


/**
 * @author 君未洋
 */
public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        //调用dao来完成查询
        return dao.findAll();
    }

    @Override
    public User login(User user) {
        return dao.login(user);
    }

    @Override
    public void addUser(User user) {
        dao.add(user);
    }

    @Override
    public void deleteUser(int id) {
        dao.delete(id);
    }

    @Override
    public User findUserById(String id) {
        return dao.findById(Integer.parseInt(id));
    }

    @Override
    public void updateUser(User user) {
        dao.update(user);
    }

    @Override
    public void delSelectedUser(String[] uids) {
        for (String uid : uids) {
            dao.delete(Integer.parseInt(uid));
        }
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows) {
        PageBean<User> pb = new PageBean<User>();
        //设置参数
        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);
        if (currentPage <= 0) {
            currentPage = 1;
            //防止跳转到后面
        }
        //调用dao查询总记录
        int totalCount = dao.findTotalCount();
        pb.setTotalCount(totalCount);
        //设置到pb中

        //5.计算总页码
        int totalPage = (totalCount % rows) == 0 ? (totalCount / rows) : (totalCount / rows + 1);
        pb.setTotalPage(totalPage);

        if (currentPage > totalPage) {
            currentPage = totalPage;
        }


        pb.setCurrentPage(currentPage);
        pb.setRows(rows);


        //这里是调用dao索引list集合
        int start = (currentPage - 1) * rows;
        List<User> list = dao.findByPage(start, rows);
        pb.setList(list);

        return pb;
    }
}
